<?php

include_once ENTITIES."laboratorio.php";

include_once MODELS."laboratorio.php";

class LaboratorioController {
    
    private $modelLaboratorio;
    
    public function __construct() {
        $this->modelLaboratorio = new LaboratorioModel();
    }
    
    public function addLaboratorio(Laboratorio $laboratorio = null){
        if(is_null($laboratorio)){
            $laboratorio = new Laboratorio();
            $this->linkLaboratorio($laboratorio);
        }
        global $config;
        if( empty($laboratorio->nome) ){
            $config->failInFunction("O campo Nome é necessários para inserção");
            $config->redirect("index.php?op=cad-labo");
        }
            
        $hasId = $config->filter("for-update-id");
        $res = false;
        
        if(empty($hasId)){
            $res = $this->modelLaboratorio->insert($laboratorio);
        } else {
            $laboratorio->id = $hasId;
            $res = $this->modelLaboratorio->update($laboratorio);
        }
        
        if($res){
            $config->successInFunction();
        } else {
            $config->failInFunction($this->modelLaboratorio->handleError());                
        }
        
        $config->redirect("index.php?op=cad-labo");
    }
    
    private function linkLaboratorio(Laboratorio &$laboratorio){
        global $config;
        $laboratorio->nome = mb_strtoupper($config->filter("nome"), 'UTF-8');
        $laboratorio->telefone = $config->filter("telefone");
        $cnpj = $config->filter("cnpj");
        $laboratorio->cnpj = str_replace(array(".","-","/"), "", $cnpj);
    }
    
    public function removerLaboratorio(){
        global $config;
        $id_laboratorio = $config->filter("labo");
        if(isset($id_laboratorio)){
            if($this->modelLaboratorio->delete($id_laboratorio)){
                $config->successInFunction();
            } else {
                $config->failInFunction($this->modelLaboratorio->handleError());
            }    
        } else {
            $config->failInFunction("Laboratório não informado");
        }
        $config->redirect("?op=cad-labo");
    }
    
    public function getAllLaboratorios(){
        return $this->modelLaboratorio->select();
    }
    
    public function getLaboratorio($id_laboratorio){
        $condition = LaboratorioModel::ID." = $id_laboratorio";
        $laboratorio = $this->modelLaboratorio->select("*", $condition);
        if(!empty($laboratorio)) return $laboratorio[0];
        return new Laboratorio();
    }
    
    
}
?>
